// Copyright 2022 Huawei Cloud Computing Technology Co., Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef CLOUDAPPSDK_CASLOG_H
#define CLOUDAPPSDK_CASLOG_H

#include <cstdio>
#include "android/log.h"
#include "pthread.h"
#include <cstring>
#include <unistd.h>
#include <securec.h>

inline char *CasStrrchr(const char *str, int c);

#define __FILENAME1__ (strcmp(CasStrrchr(__FILE__, '\\'), (char *)"") != 0 ? (CasStrrchr(__FILE__, '\\') + 1) : __FILE__)
#define __FILENAME__ (strcmp(CasStrrchr(__FILENAME1__, '/'), (char *)"") != 0 ? (CasStrrchr(__FILENAME1__, '/') + 1) : __FILENAME1__)

#define DBG(fmt, ...) LogPrint(ANDROID_LOG_DEBUG, __FILENAME__, __LINE__, __FUNCTION__, fmt, ##__VA_ARGS__)
#define INFO(fmt, ...) LogPrint(ANDROID_LOG_INFO, __FILENAME__, __LINE__, __FUNCTION__, fmt, ##__VA_ARGS__)
#define WARN(fmt, ...) LogPrint(ANDROID_LOG_WARN, __FILENAME__, __LINE__, __FUNCTION__, fmt, ##__VA_ARGS__)
#define ERR(fmt, ...) LogPrint(ANDROID_LOG_ERROR, __FILENAME__, __LINE__, __FUNCTION__, fmt, ##__VA_ARGS__)

const int LOG_BUF_SIZE = 512;

void LogToFile(int level, const char *filename, int line, const char *function, const char* msg);

inline void LogPrint(int level, const char *filename, int line, const char *function, const char *fmt, ...)
{
    if (level < ANDROID_LOG_INFO) {
        return;
    }
    char msg[LOG_BUF_SIZE] = {0};
    va_list args;
    va_start(args, fmt);
    int ret = vsnprintf_s(msg, LOG_BUF_SIZE, LOG_BUF_SIZE - 1, fmt, args);
    if (ret != -1) {
        __android_log_print(level, "CloudAppJni", "[%s:%d]%s():%s", filename, line, function, msg);
        LogToFile(level, filename, line, function, msg);
    }
    va_end(args);
}

inline char *CasStrrchr(const char *str, char c)
{
    char *ret = (char *)str;
    while (*str) {
        ++str;
    }
    while (*str != c && (str >= ret)) {
        --str;
    }
    if (str >= ret) {
        return (char *)str;
    }

    return (char *)"";
}
#endif // CLOUDAPPSDK_CASLOG_H
